package ar.org.tesis.comparticion.conocimientos.dao.hbn;



import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import ar.org.tesis.comparticion.conocimientos.pl.exceptions.DataAccessLayerException;



public abstract class AbstractDAOHbn extends HibernateDaoSupport {
	private static transient Logger logger = Logger.getLogger(AbstractDAOHbn.class);
	
	public Object getObject(Class<?> clazz, Serializable id) {
		return getHibernateTemplate().get(clazz, id);
	}
	
	public List<?> getObjects(Class<?> clazz) {
		return getHibernateTemplate().loadAll(clazz);
	}
	
	protected void save(Object obj) throws DataAccessException {
		try{
			this.getHibernateTemplate().save(obj);
		} catch (HibernateException e){
			logger.error(e);
		}
	}
	protected void saveOrUpdate(Object obj) throws DataAccessException {
		try {
			this.getHibernateTemplate().saveOrUpdate(obj);
		} catch (HibernateException e){
			logger.error(e);
		} 
	}
	protected void update(Object obj) throws DataAccessException{
		try {
			
			this.getHibernateTemplate().update(obj);

		} catch (HibernateException e){
			logger.error(e);
		} 

	}
	protected void delete(Serializable obj) throws DataAccessException{
		try {
			this.getHibernateTemplate().delete(obj);
		
		} catch (HibernateException e){
			logger.error(e);
		}
		
	}
	
	protected Object find(Class<?> clazz, Integer id) throws DataAccessException{
		Object obj = null;
		try {
		
			obj = this.getHibernateTemplate().load(clazz, id);

		} catch (HibernateException e){
			logger.error(e);
		} 
		return obj;
	}
	
	
	@SuppressWarnings("rawtypes")
	protected Query setQueryParameters(Query query, Map<String, Object> hashMap) {
		for (Iterator<?> i = hashMap.entrySet().iterator(); i.hasNext();) {
			Map.Entry e = (Map.Entry)i.next();
				query.setParameter((String)e.getKey(), e.getValue());
		}
		return query;
	}

	@SuppressWarnings("rawtypes")
	protected List<?> findAll(Class<?> clazz) {
		List<?> objects = new ArrayList();
		try {
			objects = this.getHibernateTemplate().find("from " + clazz.getName());
		} catch (HibernateException e){
			logger.error(e);
			throw new DataAccessLayerException(e);
		} 
		
		return objects;
	}
}
